package com.example.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.example.dao.CustomMapper;
import com.example.dao.SysUserMapper;
import com.example.pojo.SysUser;
import com.example.service.SysUserService;
import com.github.pagehelper.PageHelper;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

@Service
public class SysUserServiceImpl implements SysUserService {

	@Autowired
	private SysUserMapper userMapper;
	
	@Autowired
	private CustomMapper customMapper;

	@Override
	// 如果当前存在事务，则加入该事务；如果当前没有事务，则创建一个新的事务。
	@Transactional(propagation = Propagation.REQUIRED)
	public void insertUser(SysUser user) {
		userMapper.insert(user);

	}

	@Override
	// 只读，且如果当前存在事务，则加入该事务；如果当前没有事务，则以非事务的方式继续运行
	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public SysUser getUserById(String userId) {
		SysUser userById = userMapper.getUserById(userId);
		return userById;
	}
	
	@Override
	public List<SysUser> getUserByExample(Object obj) {
		Example example = Example.builder(SysUser.class).select("id","name","age","createDate").distinct()
				.andWhere(Sqls.custom().andBetween("id", obj, "181211HN6N2S86FW")).orderBy("createDate").build();

		List<SysUser> selectByExample = userMapper.selectByExample(example);
		return selectByExample;
	}

	@Override
	public List<SysUser> listUser() {
		return userMapper.selectAll();
	}

	@Override
	public void updateUser(SysUser user) {
		// selecttive是如果用户属性为空，则不去更新该属性
		userMapper.updateByPrimaryKeySelective(user);

	}

	@Override
	public List<SysUser> getUserByPage(SysUser user, Integer currentPage, Integer pageSize) {
		// 开始分页
		PageHelper.startPage(currentPage, pageSize);
		
		Example example = new Example(SysUser.class);
		Example.Criteria cr = example.createCriteria();
		if (user.getName() != null) {
			cr.andLike("name", user.getName() + "%");
			cr.andNotEqualTo("id", user.getId());
		}
		example.orderBy("createDate").asc();
		
		List<SysUser> selectByExample = userMapper.selectByExample(example);
		
		return selectByExample;
	}

	@Override
	public List<SysUser> getCustomUser() {
		return customMapper.getUserCustom();
	}

}
